package com.google.code.nexttraffic.web.openapi.impl;

import java.io.StringReader;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.google.code.nexttraffic.web.model.AreaInfoHeader;
import com.google.code.nexttraffic.web.model.AreaInfoItem;
import com.google.code.nexttraffic.web.openapi.OpenApi;

/**
 * @author ParkHaeCheol
 * 
 */
public class AreaInfoOpenApiYahooImpl implements OpenApi {

	private static final long serialVersionUID = 1L;

	private SAXBuilder builder = null;
	private StringReader stringXml = null;
	private Document xmldoc = null;
	private static AreaInfoOpenApiYahooImpl aioay;

	private AreaInfoOpenApiYahooImpl() {
	}

	public static AreaInfoOpenApiYahooImpl getInstance() {

		if (aioay == null) {
			aioay = new AreaInfoOpenApiYahooImpl();
		}

		return aioay;

	}

	@Override
	public void xmlParser(StringBuffer xmlContent) {

		builder = new SAXBuilder();

		stringXml = new StringReader((String) xmlContent.toString());

		try {
			xmldoc = builder.build(stringXml);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 책 조회
	@Override
	@SuppressWarnings("unchecked")
	public AreaInfoItem xmlItemParser() {

		Element locations = xmldoc.getRootElement().getChild("locations");
		
		List items=locations.getChildren("item");
		
		Element item = (Element) items.get(0);

		AreaInfoItem areaInfoItem = new AreaInfoItem();

		areaInfoItem.setNum(item.getChild("num").getText());
		areaInfoItem.setLatitude(item.getChild("latitude").getText());
		areaInfoItem.setLongitude(item.getChild("longitude").getText());
		areaInfoItem.setName(item.getChild("name").getText());
		areaInfoItem.setStreet(item.getChild("street").getText());
		areaInfoItem.setCity(item.getChild("city").getText());
		areaInfoItem.setCounty(item.getChild("county").getText());
		areaInfoItem.setState(item.getChild("state").getText());
		areaInfoItem.setCountry(item.getChild("country").getText());

		return areaInfoItem;
	}

	// 헤더 파싱
	@Override
	public void xmlHeaderParse() {

		Element child = xmldoc.getRootElement();

		System.out.println(child.getChildText("title"));
		System.out.println(child.getChildText("totalCount").trim());
		System.out.println(child.getChildText("result").trim());
		System.out.println(child.getChildText("sort").trim());
		System.out.println(child.getChildText("pageno").trim());
	}

	@Override
	public AreaInfoHeader getHeader() {

		return null;
	}

}